package graphics.server;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JFrame;


/**
 *
 * @author Isaac
 *
 *	This class is the main class of the server
 */
public class Mymain
{
	private static int Xsize;
	private static int Ysize;
	private static JFrame frame;
	private static Boom bmain;
	private static Vector<SingleAgent> agentsVect=new Vector<SingleAgent>();
	private static JFrame scoreFrame;
	private static ScoreBoom bScoreMain;
	/**
	 * This procedure parses the message which was accepted from the client
	 *
	 * @param in - a message to be parsed by the server
	 * @return - a message to be sent as a feedback to the client.
	 */
	public static String parseInput(String in){
		String inn =in.trim();
		String feedBack="";
		StringTokenizer st = new StringTokenizer(inn);
		if (st.hasMoreTokens()) {
			String command = st.nextToken();
			if (command.compareTo("Board")==0){ //parse board
				Xsize = Integer.parseInt(st.nextToken());
				Ysize = Integer.parseInt(st.nextToken());
				frame = new JFrame("Board");
				//create a frame for the crawler window applet
				bmain = new Boom();
				frame.add(bmain,BorderLayout.CENTER);
				frame.setSize(Xsize*46,Ysize*46);
				frame.setLocation(20,200);
				bmain.init(Xsize,Ysize);
				bmain.start();
				frame.setVisible(true);
				frame.setAlwaysOnTop(true);

				frame.addWindowListener(new WindowAdapter()
				{
					public void windowClosing(WindowEvent e)
					{
						System.exit(0);
					}
				});
				feedBack="Board Done!";
			}
			// Score Frame
			else if(command.compareToIgnoreCase("Score")==0){
				// 	TODO: get names and scores - or use names from vector
				int numOfAgents = ((Integer.parseInt(st.nextToken())));
				String[] agents = new String[numOfAgents];
				for (int i=0; i<numOfAgents; i++){
					agents[i] = st.nextToken();
				}
				
				scoreFrame = new JFrame("ScoreBoard");

				//create a frame for the crawler window applet
				bScoreMain = new ScoreBoom();
				scoreFrame.add(bScoreMain,BorderLayout.CENTER);
				scoreFrame.setSize(220,150);  //(Xsize*20,Ysize*20);
				scoreFrame.setLocation(20,20);			//	bScoreMain.init(25,25);
				bScoreMain.init(agents);
			 	bScoreMain.start();
				scoreFrame.setVisible(true);
				scoreFrame.setAlwaysOnTop(true);
				scoreFrame.setBackground(Color.LIGHT_GRAY);


			}
		// Update Score
		else if(command.compareToIgnoreCase("UpdateScore")==0){

			String name = st.nextToken();
			int newScore = ((Integer.parseInt(st.nextToken())));
			bScoreMain.updateScore(name,newScore);

		}
			else if(command.compareTo("Walls")==0){
				while(st.hasMoreTokens()){
					int cell = Integer.parseInt(st.nextToken());
					bmain.setWall(cell-1);
				}
				frame.pack();
				feedBack="Walls Done!";
			}
			else if(command.compareTo("Flags")==0){
				while(st.hasMoreTokens()){
					int cell = Integer.parseInt(st.nextToken());
					bmain.setFlag(cell-1);
				}
				feedBack="Flags Done!";
			}
			else if(command.compareTo("Ice")==0){
				while(st.hasMoreTokens()){
					int cell = Integer.parseInt(st.nextToken());
					bmain.setIce(cell-1);
				}
				feedBack="Ice Done!";
			}
			else if(command.compareTo("Agent")==0){

				String name = st.nextToken();
				String color = st.nextToken();
				String  orientation= st.nextToken();
				int cell = ((Integer.parseInt(st.nextToken()))-1);

				SingleAgent agent1 = new SingleAgent(name,color,orientation,cell,Xsize,Ysize);
				bmain.setAgent(agent1);
				agentsVect.addElement(agent1);
				feedBack="Agent Done!";
			}
			else if(command.compareTo("MoveAgent")==0){
				String agentName = st.nextToken();
				boolean found = false;
				int i=0;
				for (i=0;i<agentsVect.size() && !found;i++){
					SingleAgent tmp = agentsVect.elementAt(i);
					if(agentName.compareToIgnoreCase(tmp.getName())==0){
						found =true;
						String move = st.nextToken();
						if(move.compareToIgnoreCase("FWD") == 0){
							int newCell = tmp.getNewCell();
							bmain.deleteContent(tmp.getLocation());
							tmp.setLocation(newCell);
							bmain.setAgent(tmp);
						} else if((move.compareToIgnoreCase("RIGHT") == 0)||
								(move.compareTo("LEFT") == 0)){
							String newOrientation = tmp.getNewOrientation(move);
							bmain.deleteContent(tmp.getLocation());
							tmp.setOrientation(newOrientation);
							bmain.setAgent(tmp);
						} else if ((move.compareToIgnoreCase("NORTH") == 0) ||
								(move.compareToIgnoreCase("EAST") == 0) ||
								(move.compareToIgnoreCase("SOUTH") == 0) ||
								(move.compareToIgnoreCase("WEST") == 0)){
							tmp.setOrientation(move.toUpperCase());
							int newCell = tmp.getNewCell();
							bmain.deleteContent(tmp.getLocation());
							tmp.setLocation(newCell);
							bmain.setAgent(tmp);
						}
						else{
							feedBack="Unknown move !!!";
						}
					}
				}
				if(i >= agentsVect.size() && !found)
					feedBack="Agent not Found !!!";
			}else if(command.compareTo("TurnAgent")==0){
				String agentName = st.nextToken();
				boolean found = false;
				int i=0;
				for (i=0;i<agentsVect.size() && !found;i++){
					SingleAgent tmp = agentsVect.elementAt(i);
					if(agentName.compareToIgnoreCase(tmp.getName())==0){
						found =true;
						String move = st.nextToken();
						if ((move.compareToIgnoreCase("NORTH") == 0) ||
								(move.compareToIgnoreCase("EAST") == 0) ||
								(move.compareToIgnoreCase("SOUTH") == 0) ||
								(move.compareToIgnoreCase("WEST") == 0)){
							bmain.deleteContent(tmp.getLocation());
							tmp.setOrientation(move.toUpperCase());
							bmain.setAgent(tmp);
						} else if (move.equalsIgnoreCase("shoot")){
							
						} else{
							feedBack="Unknown move !!!";
						}
					}
				}
				if(i >= agentsVect.size() && !found)
					feedBack="Agent not Found !!!";
			}
			else{
				feedBack="Unknown command";
			}
		}
		//System.out.println("feedback = " + feedBack);
		return feedBack;
	}


	/**
	 * This is the main of the server application
	 *
	 * @param args
	 * @throws IOException
	 */
	public static void main(String args[]) throws IOException
	{
		DatagramSocket serverSocket = new DatagramSocket(9876);
		while(true)
		{
			byte[] receiveData = new byte[1024];
			byte[] sendData  = new byte[1024];
			DatagramPacket receivePacket =
				new DatagramPacket(receiveData, receiveData.length);
			serverSocket.receive(receivePacket);
			String sentence = new String(receivePacket.getData());
			sentence=parseInput(sentence);

			InetAddress IPAddress = receivePacket.getAddress();

			int port = receivePacket.getPort();

			String capitalizedSentence = sentence.toUpperCase();

			sendData = capitalizedSentence.getBytes();

			DatagramPacket sendPacket =
				new DatagramPacket(sendData, sendData.length, IPAddress,
						port);

			serverSocket.send(sendPacket);
		}
	}
}

